package demo_thread_local;

import java.util.ArrayList;

/**
 * @author: android 超级兵
 * @create: 2022-01-15 15:09
 * TODO
 **/
public class ThreadLocalClient {

    static Integer count = 1;

    static ThreadLocal<Integer> threadLocal = new ThreadLocal<Integer>() {
        // 默认值
        @Override
        protected Integer initialValue() {
            return 1;
        }
    };

    public static class MyThreadLocal extends Thread {
        int threadIndex = 0;

        public MyThreadLocal(int threadIndex) {
            this.threadIndex = threadIndex;
        }

        @Override
        public void run() {
            super.run();
            Integer count = threadLocal.get();

            count += threadIndex;

            threadLocal.set(count);
            System.out.println("ThreadName:" + getName()
                    + "\tthreadIndex:" + threadIndex // 1 2 3 4 5
                    + "\tcount:" + count
            );
//            System.out.println("ThreadName:" + getName());
        }
    }

    public static void main(String[] args) throws InterruptedException {

        ArrayList<Thread> threads = new ArrayList<>();

        for (int i = 0; i < 5; i++) {
            MyThreadLocal myThreadLocal = new MyThreadLocal(i);
            threads.add(myThreadLocal);
        }

        for (Thread thread : threads) {
            thread.start();
            // 执行完一个线程在执行另一个
            thread.join();
        }
    }
}
